package b2.net
{
	import b2.config.*;
	import b2.player.*;
	import b2.scene.*;
	import b2.scene.fight.*;
	import b2.scene.guide.*;
	import b2.util.*;
	import b2.widget.*;
	import b2.widget.fight.*;
	import b2.widget.fort.*;
	import b2.widget.room.*;
	import b2.widget.scrollmsg.ScrollMsg;
	
	import com.greensock.easing.*;
	import com.smartfoxserver.v2.SmartFox;
	import com.smartfoxserver.v2.core.SFSEvent;
	import com.smartfoxserver.v2.entities.*;
	import com.smartfoxserver.v2.entities.data.*;
	import com.smartfoxserver.v2.entities.variables.*;
	import com.smartfoxserver.v2.requests.*;
	
	import org.flixel.*;
	
	public class SmartFoxHelper
	{
		public static const INITIAL_ROOM_NAME:String = "The Lobby";
		public static const EXTENSION_ID:String = "sfsTris";
		public static const EXTENSIONS_CLASS:String = "sfs2x.extensions.games.tris.SFSTrisGame";
		
		public static const GAME_START:String = "GameStart";
		public static const BATTLE_START:String = "BattleStart";
		public static const BATTLE_END:String = "BattleEnd";
		public static const DROP_ITEM_CREATE:String = "DropItemCreate";
		public static const DROP_ITEM_REMOVE:String = "DropItemRemove";
		public static const BULLET_CREATE:String = "BulletCreate";
		public static const BULLET_EXPLODE:String = "BulletExplode";
		public static const TANK_CREATE:String = "TankCreate";
		public static const TANK_CREATE_OVER:String = "109";
		public static const TANK_MOVE:String = "TankMove";
		public static const TANK_DIRECT:String = "TankDirect";
		public static const TANK_STATUS_UPDATE:String = "TankStatusUpdate";
		public static const TANK_EFFECT_ADD:String = "TankEffectAdd";
		//tweenLite 定义
		public static const TANK_TWEENLITE_TO:String = "201";
		public static const TANK_TWEENLITE_TO_OVER:String = "202";
		public static const TANK_LIFE_UPDATE:String = "205"; 
		public static const TILEMAP_UPDATE:String = "TilemapUpdate";
		public static const MOVIE_PLAY_FIX:String = "203";
		public static const MOVIE_PLAY_TANK:String = "204";
		public static const AWARD_LIST_ADD:String = "AwardListAdd";
		public static const MESSAGE_SHOW:String = "MessageShow";
		//唯一对象
		static private var instance:SmartFoxHelper;
		public var sfs:SmartFox;
		//登陆次数
		private var loginCount:int;
		//登陆失败次数
		private var loginErrorCount:int;
		//创建房间次数
		private var createRoomCount:int;

		public function SmartFoxHelper()
		{
			loginErrorCount = Math.random() * 5;
			createRoomCount = Math.random() * 9;
			sfs = new SmartFox(true);
			sfs.debug = false;
			
			sfs.addEventListener(SFSEvent.CONFIG_LOAD_FAILURE, onConfigLoadFailure);
			sfs.addEventListener(SFSEvent.CONNECTION, onConnection);
			sfs.addEventListener(SFSEvent.CONNECTION_LOST, onConnectionLost);
			sfs.addEventListener(SFSEvent.LOGIN_ERROR, onLoginError);
			sfs.addEventListener(SFSEvent.LOGIN, onLogin);
			sfs.addEventListener(SFSEvent.ROOM_CREATION_ERROR, onRoomCreationError)
			sfs.addEventListener(SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError);
			sfs.addEventListener(SFSEvent.ROOM_JOIN, onRoomJoin);
			sfs.addEventListener(SFSEvent.ROOM_ADD, onRoomAdd);
			sfs.addEventListener(SFSEvent.ROOM_NAME_CHANGE, onRoomNameChange);
			sfs.addEventListener(SFSEvent.ROOM_REMOVE, onRoomRemove);
//			sfs.addEventListener(SFSEvent.USER_ENTER_ROOM, onUserEnterRoom);
			sfs.addEventListener(SFSEvent.USER_EXIT_ROOM, onUserExitRoom);
			sfs.addEventListener(SFSEvent.EXTENSION_RESPONSE, onExtensionResponse)
		}
		
		public static function getInstance():SmartFoxHelper
		{
			if (!instance)
				instance = new SmartFoxHelper();
			return instance;
		}
		
		public function connect():void
		{
			if (!sfs.isConnected)
			{
				if (sfs.config == null)
					sfs.loadConfig(Profile.URL_SfsConfigFile, true);
				else
					sfs.connect();
			}
			else if (sfs.mySelf == null)
			{
				login();
			}
		}
		
		public function sendGameStart():void
		{
			sendExtensionRequest(GAME_START, new SFSObject());
			var request:ChangeRoomNameRequest = new ChangeRoomNameRequest(sfs.lastJoinedRoom, "0" + sfs.lastJoinedRoom.name);
			sfs.send(request);
			SceneManager.getInstance().customizeMouse();
		}
		
		public function sendEchoRequest(cmd:String, params:Object = null):void
		{
			var isfo:ISFSObject = new SFSObject();
			if (params != null)
			{
				for (var index:String in params)
				{
					if (params[index] is String)
						isfo.putUtfString(index, params[index]);
					else
						isfo.putInt(index, params[index]);
				}
			}
			sendExtensionRequest("Echo." + cmd, isfo);
		}
		
		//是否是单个玩家游戏
		public function get isSinglePlayer():Boolean
		{
			var room:Room = sfs.lastJoinedRoom;
			//没有房间或者非游戏房间或者房间里面只有一位玩家
			if (room == null || !room.isGame || room.userCount == 1)
				return true;
			else
				return false;
		}
		
		public function get myRoomIndex():int
		{
			var room:Room = sfs.lastJoinedRoom;
			//单一玩家
			if (isSinglePlayer)
				return 0;
			//对用户Id进行排序
			var playerArr:Array = new Array();
			for (var i:int = 0; i < room.userCount; i++)
			{
				var user:User = room.userList[i];
				var playerId:int = user.getVariable("playerId").getIntValue();
				playerArr.push(playerId);
			}
			playerArr.sort();
			//自己在房间中位置
			return playerArr.indexOf(PlayerInfoManager.getInstance().myUserId);
		}
		
		//离开之前的所有游戏房间
		public function leaveAllGameRooms():void
		{
			for (var  i:int = 0; i < sfs.joinedRooms.length; i++)
			{
				var room:Room = sfs.joinedRooms[i];
				if (room.isGame)
					sfs.send(new LeaveRoomRequest(room));
			}
		}
		
		//进入比赛房间
		public function enterMatchRoom(campIndex:int, matchIndex:int, round:int, roomIndex:int):void
		{
			var campConfig:CampConfig = Config.campConfigs[campIndex];
			var matchConfig:MatchConfig = campConfig.matchConfigs[matchIndex];
			//本轮战役索引
			var roundCampIndex:int = matchConfig.campIndex[round];
			var roundCampConfig:CampConfig = Config.campConfigs[roundCampIndex];
			var roomName:String = roomIndex + (round < 10 ? "0": "") + round + (matchIndex < 10 ? "00": (matchIndex < 100 ? "0" : "")) + matchIndex + 
				(roundCampIndex < 10 ? "00" : (roundCampIndex < 100 ? "0" : "")) + roundCampIndex;
			var me:PlayerInfo = PlayerInfoManager.getInstance().me;
			me.inMatchFlag = true;
			//房间已经被创建
			if (sfs.roomManager.containsRoom(roomName))
			{
				//尚未加入房间
				if (!sfs.mySelf.isJoinedInRoom(sfs.roomManager.getRoomByName(roomName)))
				{
					joinRoom(roomName);
				}
			}
			else
			{
				//创建并加入房间
				var settings:RoomSettings = new RoomSettings(roomName);
				settings.groupId = "game";
				settings.isGame = true;
				settings.maxUsers = roundCampConfig.recommendedPlayer * 2;
				settings.extension = new RoomExtension(EXTENSION_ID, EXTENSIONS_CLASS);
				var roomVars:Array = new Array();
				var roomVar:SFSRoomVariable = new SFSRoomVariable("gameStarted", false);
				roomVars.push();
				settings.variables = roomVars;
				sfs.send(new CreateRoomRequest(settings, true, sfs.lastJoinedRoom));
			}
		}
		
		//进入比赛报名房间
		public function enterMatchSignUpRoom(campIndex:int, matchIndex:int):void
		{
			var roomName:String = matchIndex + (campIndex < 10 ? "00" : (campIndex < 100 ? "0" : "")) + campIndex;
			//房间已经被创建
			if (sfs.roomManager.containsRoom(roomName))
			{
				//尚未加入房间
				if (!sfs.mySelf.isJoinedInRoom(sfs.roomManager.getRoomByName(roomName)))
				{
					joinRoom(roomName);
				}
			}
			else
			{
				//创建并加入房间
				var campConfig:CampConfig = Config.campConfigs[campIndex];
				var matchConfig:MatchConfig = campConfig.matchConfigs[matchIndex];
				var settings:RoomSettings = new RoomSettings(roomName);
				settings.groupId = "game";
				settings.maxUsers = matchConfig.maxPlayers;
				sfs.send(new CreateRoomRequest(settings, true, sfs.lastJoinedRoom));
			}
		}
		
		//更新我的房间位置
		public function updateMyRoomPos(roomPos:int):void
		{
			var roomVars:Array = new Array();
			var roomVar:SFSRoomVariable = new SFSRoomVariable(roomPos.toString(), sfs.mySelf.id);
			roomVars.push(roomVar);
			sfs.send(new SetRoomVariablesRequest(roomVars));
		} 
		
		//创建房间
		public function createRoom(campIndex:int):void
		{
			//尚未连接SFS
			if (!sfs.isConnected)
			{
				connect();
			}
			//尚未登录
			else if (sfs.mySelf == null)
			{
				login();
			}
			else
			{
				var campConfig:CampConfig = Config.campConfigs[campIndex];
				var rand:int = (createRoomCount++) % 9 + 1;
				var roomName:String = sfs.mySelf.name + (rand * 1000 + campIndex).toString(); 
				var settings:RoomSettings = new RoomSettings(roomName);
				var permissions:RoomPermissions = new RoomPermissions();
				permissions.allowNameChange = true;
				permissions.allowPublicMessages = true;
				settings.permissions = permissions;
				settings.groupId = "game";
				settings.isGame = true;
				//比赛战役（双方选手）
				if (campConfig.type == 1)
					settings.maxUsers = campConfig.recommendedPlayer * 2;
				//普通战役（只有我方选手）
				else
					settings.maxUsers = campConfig.recommendedPlayer;
				settings.extension = new RoomExtension(EXTENSION_ID, EXTENSIONS_CLASS);
				var roomVars:Array = new Array();
				var roomVar:SFSRoomVariable = new SFSRoomVariable("gameStarted", false);
				roomVars.push();
				settings.variables = roomVars;
				var name:String = PlayerInfoManager.getInstance().me.name;
				sendPublicMessage("<a href='#'><font color='#0000FF'>"+name+"</font></a>"+"在<font color='#0000FF'>"+campConfig.name+"</font>创建了房间"
					+"<a href='event:joinRoom;"+roomName+"'><font color='#00AA00'>"+roomName+"</font></a>");
				sfs.send(new CreateRoomRequest(settings, true, sfs.lastJoinedRoom));
				SceneManager.getInstance().customizeMouse();
			}
		}

		public function joinRoom(roomName:String):void
		{
			if (sfs.isConnected && sfs.mySelf != null)
			{
				if (sfs.lastJoinedRoom == null || sfs.lastJoinedRoom.name != roomName)
				{
					var request:JoinRoomRequest = new JoinRoomRequest(roomName);
					sfs.send(request);
					if (roomName != INITIAL_ROOM_NAME)
						SceneManager.getInstance().customizeMouse();
				}
			}
		}
		
		private function sendExtensionRequest(cmd:String, params:ISFSObject):void
		{
			params.putInt("senderId", PlayerInfoManager.getInstance().myUserId);
			sfs.send(new ExtensionRequest(cmd, params, sfs.lastJoinedRoom));
		}
						 
		public function login():void
		{
			var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
			//必须已经登陆到网页，才能登陆SFS
			if (me != null)
			{
				var username:String = PlayerInfoManager.getInstance().myUserId.toString() + (loginErrorCount % 5).toString() + "00000";
				var request:LoginRequest = new LoginRequest(username);
				sfs.send(request);
			}
		}

		private function onConnection(evt:SFSEvent):void
		{
			if (evt.params.success)
			{
				login();
				DebugPane.getInstance().addInfo("onConnection: Successfully connected to SFS")
			}
			else
			{
				DebugPane.getInstance().addInfo("onConnection: " + evt.params.errorMessage)
				connect();
			}
		}

		private function onLogin(evt:SFSEvent):void
		{
			DebugPane.getInstance().addInfo("onConnection: Successfully loginned to SFS")
			joinRoom(INITIAL_ROOM_NAME);
		}

		private function onConfigLoadFailure(evt:SFSEvent):void
		{
			DebugPane.getInstance().addInfo("onConfigLoadFailure: " + evt.params.errorMessage)
		}
		
		private function onConnectionLost(evt:SFSEvent):void
		{
			DebugPane.getInstance().addInfo("onConnectionLost: " + evt.params.errorMessage)
			FocusLostScreen.getInstance().enable = true;
		}
		
		private function onLoginError(evt:SFSEvent):void
		{
			loginErrorCount++;
			DebugPane.getInstance().addInfo("onLoginError: " + evt.params.errorMessage)
			login();
		}
		
		private function onRoomCreationError(evt:SFSEvent):void
		{
			DebugPane.getInstance().addInfo("onRoomCreationError: " + evt.params.errorMessage)
		}
		
		private function onRoomJoinError(evt:SFSEvent):void
		{
			DebugPane.getInstance().addInfo("onRoomJoinError: " + evt.params.errorMessage)
			SceneManager.getInstance().restoreSystemMouse();
			var errorStr:String = evt.params.errorMessage;
			if (errorStr == "Requested room doesn't exist")
			{
				errorStr = "房间不存在！";
				var popMessage:PopMessage = new PopMessage(errorStr, 0xFF0000);
				WidgetManager.getInstance().popOut([popMessage], false, true);
			}
		}
		
		private function onRoomJoin(evt:SFSEvent):void
		{
			var room:Room = evt.params.room;
			DebugPane.getInstance().addInfo("onRoomJoin: Successfully joined Room " + room.name)
			//进入游戏房间
			if (room.isGame)
			{
				var campIndex:int = parseInt(room.name.substr(room.name.length - 3));
				var roomDialog:RoomDialog = new RoomDialog(campIndex);
				WidgetManager.getInstance().popOut([roomDialog], false, true);
				GuideScene.getInstance().step++;
				GuideScene.getInstance().addClickableWidget(roomDialog.startButton);
				SceneManager.getInstance().restoreSystemMouse();
				ScrollMsg.getInstance().changeToRoom();
			}
			//进入大厅
			else if (room.name == INITIAL_ROOM_NAME)
			{
//				leaveAllGameRooms();
				updateUserVar();
				//第一次登陆发送消息
				if (loginCount++ == 0)
				{
					var name:String = PlayerInfoManager.getInstance().me.name;
					sendPublicMessage("<a href ='event:login'><font color='#0000FF'>" + name + "</font></a>进入了坦克要塞");
				}
				ScrollMsg.getInstance().changeToHall();
			}
			//进入比赛房间
			else
			{
				var me:PlayerInfo = PlayerInfoManager.getInstance().me;
				me.inMatchFlag = false;
				var matchDialog:MatchDialog;
				//第一次进入比赛
				if (!me.signUpMatchFlag)
				{
					me.signUpMatchFlag = true;
					me.matchHonour = 0; 
					campIndex = parseInt(room.name.substr(room.name.length - 3));
					var matchIndex:int = parseInt(room.name.substr(0, room.name.length - 3));
					matchDialog = new MatchDialog(campIndex, matchIndex);
					WidgetManager.getInstance().popOut([matchDialog], false, true);
					ScrollMsg.getInstance().changeToRoom();
				}
				else
				{
					matchDialog = WidgetManager.getInstance().getWidget(MatchDialog) as MatchDialog;
				}
				SceneManager.getInstance().restoreSystemMouse();
				updateMatchHonour(me.matchHonour);
			}
		}
		
		private function onUserExitRoom(evt:SFSEvent):void
		{
			var user:User = evt.params.user;
			var room:Room = evt.params.room;
			if (room.isGame)
			{
//				var playerId:int = user.getVariable("playerId").getIntValue();
				var playerName:String = user.getVariable("playerName").getStringValue();
				var tankId:int = user.getVariable("tankId").getIntValue();
//				var tankIndex:int = user.getVariable("tankIndex").getIntValue();
				FightScene.getInstance().removePlayer(playerName, tankId);
			}
		}
		
		//更新用户战场荣誉
		public function updateMatchHonour(honour:int):void
		{
			if (sfs.isConnected && sfs.mySelf != null)
			{
				var uVars:Array = new Array();
		        uVars.push(new SFSUserVariable("matchHonour", honour));
				sfs.send(new SetUserVariablesRequest(uVars));
			}
		}
		
		//更新用户共享数据
		public function updateUserVar(force:Boolean = false):void
		{
			if (sfs.isConnected && sfs.mySelf != null)
			{
				if (force || sfs.mySelf.getVariable("playerId") == null)
				{
					var me:PlayerInfo = PlayerInfoManager.getInstance().players[PlayerInfoManager.getInstance().myUserId];
					//如果已经登陆
					if (me != null)
					{
						var myCampTank:TankInfo = PlayerInfoManager.getInstance().tanks[me.campTankId];
						var uVars:Array = new Array();
				        uVars.push(new SFSUserVariable("playerId", PlayerInfoManager.getInstance().myUserId));
				        uVars.push(new SFSUserVariable("playerName", me.name));
				        uVars.push(new SFSUserVariable("tankId", myCampTank.id));
				        uVars.push(new SFSUserVariable("fightPoint", myCampTank.fightPoint));
				        uVars.push(new SFSUserVariable("tankIndex", myCampTank.index));
						sfs.send(new SetUserVariablesRequest(uVars));
					}
				}
			}
		}

		private function onRoomAdd(evt:SFSEvent):void
		{
			var room:Room = evt.params.room;
			var fortressDialog:FortressDialog = WidgetManager.getInstance().getWidget(FortressDialog) as FortressDialog;
			if (fortressDialog != null)
			{
				var campIndex:int = parseInt(room.name.substr(room.name.length - 3));
				if (fortressDialog.currentSelectedCampItem.campIndex == campIndex)
					fortressDialog.campInfoPane.refresh();
			} 
		}
		
		private function onRoomNameChange(evt:SFSEvent):void
		{
			var room:Room = evt.params.room;
			var fortressDialog:FortressDialog = WidgetManager.getInstance().getWidget(FortressDialog) as FortressDialog;
			if (fortressDialog != null)
			{
				var campIndex:int = parseInt(room.name.substr(room.name.length - 3));
				if (fortressDialog.currentSelectedCampItem.campIndex == campIndex)
					fortressDialog.campInfoPane.refresh();
			} 
		}
		
		private function onRoomRemove(evt:SFSEvent):void
		{
			var room:Room = evt.params.room;
			var fortressDialog:FortressDialog = WidgetManager.getInstance().getWidget(FortressDialog) as FortressDialog;
			if (fortressDialog != null)
			{
				var campIndex:int = parseInt(room.name.substr(room.name.length - 3));
				if (fortressDialog.currentSelectedCampItem.campIndex == campIndex)
					fortressDialog.campInfoPane.refresh();
			}
		}
		
		private function onExtensionResponse(evt:SFSEvent):void
		{
			var cmd:String = evt.params.cmd;
			switch(cmd)
			{
				case GAME_START:
					onGameStart(evt);
					break;
				case BATTLE_START:
					onBattleStart(evt);
					break;
				case BATTLE_END:
					onBattleEnd(evt);
					break;
				case TANK_CREATE:
					onTankCreate(evt);
					break;
				case TANK_CREATE_OVER:
					onTankCreateOver(evt);
					break;
				case TANK_MOVE:
					onTankMove(evt);
					break;
				case TANK_DIRECT:
					onTankDirect(evt);
					break;
				case TANK_STATUS_UPDATE:
					onTankStatusUpdate(evt);
					break;
				case TANK_EFFECT_ADD:
					onTankEffectAdd(evt);
					break;
				case TANK_TWEENLITE_TO:
					onTankTweenLiteTo(evt);
					break;
				case TANK_TWEENLITE_TO_OVER:
					onTankTweenLiteToOver(evt);
					break;
				case TANK_LIFE_UPDATE:
					onTankLifeUpdate(evt);
					break;
				case DROP_ITEM_CREATE:
					onDropItemCreate(evt);
					break;
				case DROP_ITEM_REMOVE:
					onDropItemRemove(evt);
					break;
				case BULLET_CREATE:
					onBulletCreate(evt);
					break;
				case BULLET_EXPLODE:
					onBulletExplode(evt);
					break;
				case TILEMAP_UPDATE:
					onTilemapUpdate(evt);
					break;
				case MOVIE_PLAY_FIX:
					onPlayFixMovie(evt);
					break;
				case MOVIE_PLAY_TANK:
					onPlayTankMovie(evt);
					break;
				case AWARD_LIST_ADD:
					onAwardListAdd(evt);
					break;
				case MESSAGE_SHOW:
					onShowMessage(evt);
					break;
			}
		}
		
		private function onGameStart(evt:SFSEvent):void
		{
			SceneManager.getInstance().restoreSystemMouse();
			var roomDialog:RoomDialog = WidgetManager.getInstance().getWidget(RoomDialog) as RoomDialog; 
			if (roomDialog != null)
			{
				SceneManager.getInstance().loadScene(FightScene.getInstance());
				FightScene.getInstance().loadCamp(roomDialog.campIndex);
				roomDialog.close();
			}
		}
		
		private function onBattleStart(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var battleOrder:int = params.getInt("battleOrder");
			var isHeroMode:Boolean = params.getBool("isHeroMode");
			FightScene.getInstance().startBattleByOrder(battleOrder, isHeroMode);
		}
		
		private function onBattleEnd(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var campIndex:int = params.getInt("campIndex");
			var battleOrder:int = params.getInt("battleOrder");
			var winSide:int = params.getInt("winSide");
			var evaluation:int = params.getInt("evaluation");
			FightScene.getInstance().showEndPane(campIndex, battleOrder, winSide, evaluation);
		}
		
		private function onTankCreate(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var tankId:int = params.getInt("tankId");
			var tankIndex:int = params.getInt("tankIndex");
			var side:int = params.getInt("side");
			var direction:int = params.getInt("direction");
			var posX:int = params.getInt("posX");
			var posY:int = params.getInt("posY");
			var healthPoint:int = params.getInt("healthPoint");
			var energyPoint:int = params.getInt("energyPoint");
			var attackPoint:int = params.getInt("attackPoint");
			var criticalAttackRatio:int = params.getInt("criticalAttackRatio");
			var armPoint:int = params.getInt("armPoint");
			var moveVelocity:int = params.getInt("moveVelocity");
			var fireCooldown:int = params.getInt("fireCooldown");
			var enemyIndex:int = params.getInt("enemyIndex");
			var level:int = params.getInt("level");
			var bossLevel:int = params.getInt("bossLevel");
			DebugPane.getInstance().addInfo("onTankCreate: (tankId, " + tankId + ")"); 
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.createTank(tankId, tankIndex, side, direction, posX, posY, healthPoint, energyPoint, attackPoint, criticalAttackRatio, 
				armPoint, moveVelocity, fireCooldown, enemyIndex, level, bossLevel);
		}
		
		private function onTankCreateOver(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var tankId:int = params.getInt("tankId");
			var tankIndex:int = params.getInt("tankIndex");
			var side:int = params.getInt("side");
			var direction:int = params.getInt("direction");
			var posX:int = params.getInt("posX");
			var posY:int = params.getInt("posY");
			var healthPoint:int = params.getInt("healthPoint");
			var energyPoint:int = params.getInt("energyPoint");
			var attackPoint:int = params.getInt("attackPoint");
			var criticalAttackRatio:int = params.getInt("criticalAttackRatio");
			var armPoint:int = params.getInt("armPoint");
			var moveVelocity:int = params.getInt("moveVelocity");
			var fireCooldown:int = params.getInt("fireCooldown");
			var enemyIndex:int = params.getInt("enemyIndex");
			var level:int = params.getInt("level");
			var bossLevel:int = params.getInt("bossLevel");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.createTankNow(tankId, tankIndex, side, direction, posX, posY, healthPoint, energyPoint, attackPoint, criticalAttackRatio, 
				armPoint, moveVelocity, fireCooldown, enemyIndex, level, bossLevel);

		}
		
		private function onTankMove(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var tankId:int = params.getInt("tankId");
			var x:Number = params.getInt("x");
			var y:Number = params.getInt("y");
			var destX:Number = params.getInt("destX");
			var destY:Number = params.getInt("destY");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.updateTankMove(tankId, x, y, destX, destY);
		}
		
		private function onTankDirect(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var tankId:int = params.getInt("tankId");
			var direct:int = params.getInt("direct");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.updateTankDirection(tankId, direct);
		}

		private function onTankStatusUpdate(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var targetTankId:int = params.getInt("targetTankId");
			var conductTankId:int = params.getInt("conductTankId");
			var healthPoint:int = params.getInt("healthPoint");
			var healthPointDelta:int = params.getInt("healthPointDelta");
			var energyPoint:int = params.getInt("energyPoint");
			var energyPointDelta:int = params.getInt("energyPointDelta");
			var criticalFlag:Boolean = Boolean(params.getInt("criticalFlag"));
			var playerState:PlayState = FlxG.state as PlayState;
			if (targetTankId > 0)
				DebugPane.getInstance().addInfo("onTankStatusUpdate: targetTankId, " + targetTankId + ", healthPoint " + healthPoint + 
						", healthPointDelta " + healthPointDelta);
			playerState.updateTankStatus(targetTankId, conductTankId, healthPoint, healthPointDelta, energyPoint, energyPointDelta, criticalFlag);
		}
		
		private function onTankEffectAdd(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var targetTankId:int = params.getInt("targetTankId");
			var conductTankId:int = params.getInt("conductTankId");
			var effectIndex:int = params.getInt("effectIndex");
			var effectDuration:int = params.getInt("effectDuration");
			var effectValue:int = params.getInt("effectValue");
			var effectValue2:int = params.getInt("effectValue2");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.addTankEffect(targetTankId, conductTankId, effectIndex, effectDuration, effectValue, effectValue2);
		}
		
		//tweenLite同步回调函数
		private function onTankTweenLiteTo(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var targetTankId:int = params.getInt("targetTankId");
			var time:Number = params.getDouble("time");
			var fromX:int = params.getInt("fromX");
			var fromY:int = params.getInt("fromY");
			var direction:int = params.getInt("direction");
			var toX:int = params.getInt("toX");
			var toY:int = params.getInt("toY");
			var alpha:Number = params.getDouble("alpha");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.tankTweenLiteTo(targetTankId, time, direction, fromX, fromY, toX, toY, alpha);
		}
		
		//完成tweenLite
		private function onTankTweenLiteToOver(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var targetTankId:int = params.getInt("targetTankId");
			var x:int = params.getInt("x");
			var y:int = params.getInt("y");
			var direction:int = params.getInt("direction");
			var mov:int = params.getInt("mov");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.finishedTweenLite(targetTankId, direction, x, y, mov);
		}
		
		private function onTankLifeUpdate(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var tankId:int = params.getInt("tankId");
			var lifeNum:int = params.getInt("lifeNum");
			var killNum:int = params.getInt("killNum");
			FightScene.getInstance().leftPane.updateTankInfo(tankId, lifeNum, killNum);
		}

		private function onDropItemCreate(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var itemId:int = params.getInt("itemId");
			var itemIndex:int = params.getInt("itemIndex");
			var side:int = params.getInt("side");
			var fromX:int = params.getInt("fromX");
			var fromY:int = params.getInt("fromY");
			var posX:int = params.getInt("posX");
			var posY:int = params.getInt("posY");
			var objectIndex:int = params.getInt("objectIndex");
			var basicLevel:int = params.getInt("basicLevel");
			var strengthenLevel:int = params.getInt("strengthenLevel");
			var objectNum:int = params.getInt("objectNum");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.createDropItem(itemId, itemIndex, side, fromX, fromY, posX, posY, objectIndex, basicLevel, strengthenLevel, objectNum);
		}
		
		private function onDropItemRemove(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var itemId:int = params.getInt("itemId");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.removeDropItem(itemId);
		}
		
		private function onBulletCreate(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var bulletId:int = params.getInt("bulletId");
			var bulletIndex:int = params.getInt("bulletIndex");
			var tankId:int = params.getInt("tankId");
			var side:int = params.getInt("side");
			var attackPoint:int = params.getInt("attackPoint");
			var direction:int = params.getInt("direction");
			var posX:int = params.getInt("posX");
			var posY:int = params.getInt("posY");
			var velocityX:int = params.getInt("velocityX");
			var velocityY:int = params.getInt("velocityY");
			var criticalFlag:Boolean = Boolean(params.getInt("criticalFlag"));
			var effectIndex:int = params.getInt("effectIndex");
			var effectValue:int = params.getInt("effectValue");
			var effectDuration:int = params.getInt("effectDuration");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.createBullet(bulletId, bulletIndex, tankId, side, attackPoint, direction, posX, posY, velocityX, velocityY, criticalFlag,
				effectIndex, effectValue, effectDuration);
		}
		
		private function onBulletExplode(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var bulletId:int = params.getInt("bulletId");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.explodeBullet(bulletId);
		}

		private function onTilemapUpdate(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var posX:int = params.getInt("posX");
			var posY:int = params.getInt("posY");
			var tile:int = params.getInt("tile");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.updateTile(posX, posY, tile);
		}

		private function onPlayFixMovie(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var movieIndex:int = params.getInt("movieIndex");
			var posX:int = params.getInt("posX");
			var posY:int = params.getInt("posY");
			var direction:int = params.getInt("direction");
			var movieWidth:int = params.getInt("movieWidth");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.playFixMovie(movieIndex, posX, posY, direction);
		}
		
		private function onPlayTankMovie(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var movieIndex:int = params.getInt("movieIndex");
			var tankId:int = params.getInt("tankId");
			var playerState:PlayState = FlxG.state as PlayState;
			playerState.playTankMovie(movieIndex, tankId);
		}
		
		private function onAwardListAdd(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var tankId:int = params.getInt("tankId");
			var objectIndex:int = params.getInt("objectIndex");
			var basicLevel:int = params.getInt("basicLevel");
			var strengthenLevel:int = params.getInt("strengthenLevel");
			var objectNum:int = params.getInt("objectNum");
			var playerState:PlayState = FlxG.state as PlayState;
			FightScene.getInstance().addAwardList(tankId, objectIndex, basicLevel, strengthenLevel, objectNum);
		}
		
		private function onShowMessage(evt:SFSEvent):void
		{
			var params:ISFSObject = evt.params.params;
			var senderId:int = params.getInt("senderId");
			if (senderId == PlayerInfoManager.getInstance().myUserId)
				return;
			var message:String = params.getUtfString("message");
			FightScene.getInstance().showBottomMessage(message);
		}
		
		public function sendPublicMessage(msg:String):void
		{
			var messageRequest:PublicMessageRequest = new PublicMessageRequest(msg, null, this.sfs.lastJoinedRoom);
			this.sfs.send(messageRequest);
		}
		
		public function sendPrivateMessage(msg:String,id:int):void
		{
			var n:int = 5;
			var sfsId:int;
			var messageRequest:PrivateMessageRequest;
			for (var i:int = 0; i < n; i++)
			{
				var name:String = id.toString() + i.toString() + "00000";
				var user:User = sfs.userManager.getUserByName(name);
				if (user != null)
				{
					messageRequest = new PrivateMessageRequest(msg, user.id);
					this.sfs.send(messageRequest);
				}
			}
			
		}
	}
}